package com.liu.redisson.business.controller;

import com.liu.redisson.business.domain.bo.UpdateStockReqBO;
import com.liu.redisson.business.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author liujiazhong
 * @date 2020/4/23 11:35
 */
@Slf4j
@RestController
public class StockController {

    private static final Integer MAX_THREAD = 500;

    private final StockService stockService;

    public StockController(StockService stockService) {
        this.stockService = stockService;
    }

    private CyclicBarrier cyclicBarrier = new CyclicBarrier(MAX_THREAD);

    @GetMapping("do-stock")
    public void doStock() {
        for (int i = 0; i < MAX_THREAD; i++) {
            new Thread(() -> {
                try {
                    cyclicBarrier.await();
                    stockService.doStock(UpdateStockReqBO.builder().productId(1001L).build());
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
            ).start();
        }
    }

}
